﻿using Microsoft.ServiceModel.Web;
using System.ServiceModel.Channels;
using Neptuno.Model;
using Neptuno.Component;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Configuration;
using Neptuno.Model.Utilities;
using System.Data.Objects;

namespace Neptuno.Service.Security
{
    public class BasicAuthenticationInterceptor : RequestInterceptor
    {
        private Usuarios Usuario = null;
        HttpRequestMessageProperty Request;

        public BasicAuthenticationInterceptor() : base(false) { }

        public override void ProcessRequest(ref RequestContext requestContext)
        {
            Request = (HttpRequestMessageProperty)requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name];
            isValidUser();

            string url = requestContext.RequestMessage.Headers.To.LocalPath;
            hasPrivileges(url);

            this.AddLogs(url, requestContext.RequestMessage.ToString());

            return;
        }

        private void isValidUser()
        {
            string username = this.Request.Headers["username"];
            string password = this.Request.Headers["password"];

            AutenticacionComponent Component = new AutenticacionComponent(username, password);
            this.Usuario = Component.GetUsuario();
            CurrentUser.Name = this.Usuario.userName;
        }

        private void hasPrivileges(string url)
        {
            string route = url.Substring(1, url.LastIndexOf("/") - 1);
            List<Privilegios> Privilegios = new List<Privilegios>();

            Usuario.UsuariosEnRol.Select(t => t.Roles).ToList().ForEach(t => Privilegios.AddRange(t.Privilegios));

            Privilegios Privilegio = Privilegios.SingleOrDefault(t => t.method == Request.Method.ToUpper() && t.route == route);

            if (Privilegio == new Privilegios())
            {
                throw new Exception("Privilegios insuficientes");
            }
        }

        private void AddLogs(string url, string body)
        {
            LogsComponent Component = new LogsComponent();

            Component.AgregarLog(new Logs
            {
                userName = Usuario.userName,
                url = url,
                method = Request.Method,
                body = body,
                activityDay = DateTime.Now
            });
                    
        }
    }
}